package com.gdpu.liou.symphonyserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.gdpu.liou.symphonyserver.entity.respose.Response;
import com.gdpu.liou.symphonyserver.entity.Singer;
import com.gdpu.liou.symphonyserver.entity.respose.ResponseCode;
import com.gdpu.liou.symphonyserver.service.SingerService;
import com.gdpu.liou.symphonyserver.common.utils.Consts;
import com.gdpu.liou.symphonyserver.common.utils.PagingUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author liou
 */
@RestController
@RequestMapping("/singer")
@Slf4j
public class SingerController {
    private final SingerService singerService;

    public SingerController(SingerService singerService) {
        this.singerService = singerService;
    }

    /**
     * 添加歌手
     */
    
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public Object addSinger(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        //接受singer数据
        String name = request.getParameter("name").trim();
        String sex = request.getParameter("sex").trim();
        String birth = request.getParameter("birth").trim();
        String location = request.getParameter("location").trim();
        String introduction = request.getParameter("introduction").trim();
        //将String格式birth转换Date格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate = new Date();
        try {
            birthDate = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //将数据封装成singer对象
        Singer singer = new Singer();
        singer.setName(name);
        singer.setSex(new Byte(sex));
        singer.setPic("/img/otherPic/默认.jpeg");
        singer.setBirth(birthDate);
        singer.setLocation(location);
        singer.setIntroduction(introduction);
        //添加歌手
        boolean flag = singerService.insert(singer);
        //添加成功
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "添加成功");
            return jsonObject;
        }
        //添加失败
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "添加失败");
        return jsonObject;
    }

    /**
     * 修改歌手
     */
    
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object updateSinger(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        //接受singer数据
        String id = request.getParameter("id").trim();
        String name = request.getParameter("name").trim();
        String sex = request.getParameter("sex").trim();
        String birth = request.getParameter("birth").trim();
        String location = request.getParameter("location").trim();
        String introduction = request.getParameter("introduction").trim();
        //将String格式birth转换Date格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate = new Date();
        try {
            birthDate = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //将数据封装成singer对象
        Singer singer = new Singer();
        singer.setId(Integer.parseInt(id));
        singer.setName(name);
        singer.setSex(new Byte(sex));
        singer.setBirth(birthDate);
        singer.setLocation(location);
        singer.setIntroduction(introduction);
        //修改歌手
        boolean flag = singerService.update(singer);
        //修改成功
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "修改成功");
            return jsonObject;
        }
        //修改失败
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "修改失败");
        return jsonObject;
    }


    /**
     * 删除歌手
     */
    
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Object deleteSinger(String id) {
        JSONObject jsonObject = new JSONObject();
        //删除歌手
        boolean flag = singerService.delete(Integer.parseInt(id));
        //删除成功
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "删除成功");
            return jsonObject;
        }
        //删除失败
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "删除失败");
        return jsonObject;
    }

    /**
     * 查询歌手：根据主键
     */
    
    @RequestMapping(value = "/selectSingerById",method = RequestMethod.GET)
    public Response selectBySingerId(@RequestParam Integer id) {
        try {
            Singer singer = singerService.selectBySingerId(id);
            if(Optional.ofNullable(singer).isPresent()){
                return new Response<Singer>(singer);
            }
            return new Response<Singer>(200, "数据库不存在该歌手");
        } catch (Exception e) {
            log.error("请求查询歌手失败", e);
            return new Response<>(ResponseCode.SERVER_ERROR);
        }
    }

    /**
     * 查询所有歌手
     */
    
    @RequestMapping(value = "/selectAllSinger", method = RequestMethod.GET)
    public Response selectAllSinger() {
        try {
            List<Singer> singers = singerService.selectAllSinger();
            int count = CollectionUtils.isEmpty(singers) ? 0 : singers.size();
            return new Response<>(singers, count);
        } catch (Exception e) {
            log.error("请求查询所有歌手失败", e);
            return new Response<>(ResponseCode.SERVER_ERROR);
        }
    }


    /**
     * 分页查询歌手
     */
    
    @RequestMapping(value = "/pagingQuerySinger", method = RequestMethod.GET)
    public PagingUtil pagingQuerySinger(Integer currentPage, String name) {
        return singerService.pagingQuerySinger(currentPage, name);
    }

    /**
     * 查询歌手集合：根据名字模糊查询
     */
    
    @RequestMapping(value = "/selectByName", method = RequestMethod.GET)
    public List<Singer> selectByName(String name) {
        return singerService.selectByName(name);
    }

    /**
     * 查询歌手集合：根据性别
     */
    
    @RequestMapping("/selectBySex")
    public List<Singer> selectBySex(String sex) {
        return singerService.selectBySex(Integer.parseInt(sex));
    }

    /**
     * 更新歌手图片
     */

    @RequestMapping(value = "/updateSingerPic", method = RequestMethod.POST)
    public Object updateSingerPic(@RequestParam("file") MultipartFile file, @RequestParam("id") int id) {
        JSONObject jsonObject = new JSONObject();
        if (file.isEmpty()) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "文件上传失败");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        //文件存储路径
        String filePath = System.getProperty("user.dir") +
                System.getProperty("file.separator") + "static" +
                System.getProperty("file.separator") + "img"
                + System.getProperty("file.separator") + "singerPic";
        //文件存储
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        log.info("文件上传路径：{}", filePath);
        //存储到数据库里的相对文件地址
        String storePortraitPath = "/img/singerPic/" + fileName;
        try {
            file.transferTo(dest);
            Singer singer = new Singer();
            singer.setId(id);
            singer.setPic(storePortraitPath);
            boolean flag = singerService.update(singer);
            if (flag) {
                jsonObject.put(Consts.CODE, 1);
                jsonObject.put(Consts.MSG, "上传成功");
                jsonObject.put("pic", storePortraitPath);
                return jsonObject;
            }
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "上传失败");
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "上传失败" + e.getMessage());
        } finally {
            return jsonObject;
        }
    }
    
    @RequestMapping(value = "/selectSingerSelected", method = RequestMethod.GET)
    public Response selectSingerSelected() {
        try {
            List<Singer> singers = singerService.selectSingerSelected();
            return new Response<List<Singer>>(200, "成功", singers, 1);
        } catch (Exception e) {
            log.error("请求精选歌手列表失败", e);
            return new Response(ResponseCode.SERVER_ERROR);
        }
    }


}
